package com.zgm.ch04._2_1_2;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

/**
 * 嵌入Bean的创建的两种方法：
 * 方法二：
 * 实现InitializingBean接口
 * @author Administrator
 *
 */
public class SimpleBean implements InitializingBean {

	private String name;
	private int age;
	
//	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("自定义初始化开始");
		if(this.name == null || "".equals(this.name)){
			System.out.println("没有指定name");
			this.name = "zgm";
		}
		
		if(this.age ==0){
			throw new IllegalArgumentException("你必须为类" + this.getClass() + "指定值！");
		}
	}

	public void init(){
		System.out.println("自定义初始化开始2");
		if(this.name == null || "".equals(this.name)){
			System.out.println("没有指定name");
			this.name = "zgm";
		}
		
		if(this.age ==0){
			throw new IllegalArgumentException("你必须为类" + this.getClass() + "指定值！");
		}
	}
	
	public static void main(String[] args){
//		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("/META-INF/spring/ch03/_4_11/_4_11-context.xml"));
		//可以
		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("com/zgm/ch04/_2_1_2/_2_1_2-context.xml"));
		//不行 
//		BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("classpath:com/zgm/ch03/_4_11/_4_11-context.xml"));
		
		SimpleBean simpleBean2 = (SimpleBean) beanFactory.getBean("simpleBean2");
		SimpleBean simpleBean = (SimpleBean) beanFactory.getBean("simpleBean");
		SimpleBean simpleBean3 = (SimpleBean) beanFactory.getBean("simpleBean2");
		System.out.println("simpleBean == simpleBean2 is " + (simpleBean == simpleBean2));
		System.out.println("simpleBean3 == simpleBean2 is " + (simpleBean3 == simpleBean2));
//		SimpleBean simpleBean2 = (SimpleBean) beanFactory.getBean("simpleBean2");
//		System.out.println(simpleBean);
	}
	
	@Override
	public String toString(){
		final StringBuilder sb = new StringBuilder();
		sb.append("SimpleBean");
		sb.append("{name=").append(name);
		sb.append(", age=").append(age);
		sb.append("}");
		
		return sb.toString();
		
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	
	
	
}
